---
title: Get Started
icon: Album
---

## Introduction

The serializer is a library that allows you to serialize instances of classes to objects. It is designed to be used in Project Graph to save and load projects.

This package provides few decorators to make it easy to flag properties and methods that should be serialized, and to customize how to pass arguments to the constructor when deserializing.

## Requirements

You need to enable `experimentalDecorators` and `emitDecoratorMetadata` in your `tsconfig.json`.

## Installation

```sh
npm install @graphif/serializer
# or use pnpm
pnpm add @graphif/serializer
```

## Basic Usage

Here is a class `Person`:

```ts
class Person {
  private isGreeting: boolean = false;

  constructor(
    public name: string,
    public age: number,
  ) {}

  greet() {
    this.isGreeting = true;
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    this.isGreeting = false;
  }
}
```

We want to include `name` and `age` in the serialized object, but not `isGreeting`. We can use the `@serializable` decorator to flag `name` and `age` as serializable:

<Callout>
  Because of technical limitations, you **cannot** use the `@serializable` decorator on arguments of the constructor.
</Callout>

```ts
import { serializable } from "@graphif/serializer";

class Person {
  @serializable
  public name: string;
  @serializable
  public age: number;

  private isGreeting: boolean = false;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet() {
    this.isGreeting = true;
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    this.isGreeting = false;
  }
}
```

Now we can serialize an instance of `Person` to an object:

```ts
import { serialize } from "@graphif/serializer";

const person = new Person("Alice", 25);
const serialized = serialize(person);
console.log(serialized);
```

This will output the serialized object, without prototypes:

```json
{
  "_": "Person",
  "name": "Alice",
  "age": 25
}
```

You can save this object via `JSON.stringify` or MsgPack.

<Callout>
  Every object (including nested) has a `_` property that contains the name of the class. This is used to determine the
  class when deserializing.
</Callout>

We can also deserialize the object back to an instance of `Person`:

```ts
import { deserialize } from "@graphif/serializer";

const deserialized = deserialize(serialized);
console.log(deserialized);
```

This will output:

```ts
Person { name: "Alice", age: 25 }
```
